package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dto.ClassQueryRequest;
import com.itheima.dto.PageBean;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.ClassMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Student;
import com.itheima.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClassServiceImpl implements ClassService {

    @Autowired
    private ClassMapper classMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageBean<Clazz> page(ClassQueryRequest classQueryRequest) {
        PageHelper.startPage(classQueryRequest.getPage(),classQueryRequest.getPageSize());
        Page<Clazz> page=classMapper.getClazzsByNameAndTime(classQueryRequest);
        return new PageBean<>(page.getTotal(),page.getResult());
    }

    @Override
    public void insert(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        classMapper.insert(clazz);
    }

    @Override
    public Clazz getById(Integer id) {
        Clazz clazz=classMapper.getById(id);
        return clazz;
    }

    @Override
    public void update(Clazz clazz) {
        classMapper.update(clazz);
    }

    @Override
    public void delete(Integer id) {
        List<Student> stus = studentMapper.getByClassId(id);
        if (stus!=null) {
            throw new BusinessException("班级下有学生，不能删除");
        }
        classMapper.deleteById(id);
    }

    @Override
    public List<Clazz> getClazzs() {
        return classMapper.getClazzs();
    }


}
